<template>
  <div class="api-example">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>API调用示例</span>
        </div>
      </template>
      
      <div class="card-content">
        <!-- 商品搜索示例 -->
        <div class="example-section">
          <h3>商品搜索</h3>
          <el-input v-model="searchKeyword" placeholder="请输入关键词搜索商品" style="width: 300px; margin-right: 10px" />
          <el-button type="primary" @click="searchProducts">搜索</el-button>
          <el-table v-if="products.length > 0" :data="products" style="width: 100%; margin-top: 15px">
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="name" label="商品名称" />
            <el-table-column prop="price" label="价格" />
            <el-table-column prop="stock" label="库存" />
            <el-table-column prop="status" label="状态">
              <template #default="scope">
                {{ scope.row.status === 1 ? '上架' : '下架' }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120">
              <template #default="scope">
                <el-button type="primary" size="small" @click="addProductToCart(scope.row)">加入购物车</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <!-- 购物车示例 -->
        <div class="example-section">
          <h3>购物车</h3>
          <el-button type="primary" @click="getCartItems">查看购物车</el-button>
          <div v-if="cartItems.length > 0" class="cart-items">
            <div v-for="item in cartItems" :key="item.id" class="cart-item">
              <span>{{ item.productName }}</span>
              <span>数量: {{ item.quantity }}</span>
              <span>单价: {{ item.price }}</span>
              <span>小计: {{ item.price * item.quantity }}</span>
              <el-button type="danger" size="small" @click="removeFromCart(item.id)">删除</el-button>
            </div>
          </div>
          <p v-else>购物车为空</p>
        </div>
        
        <!-- 订单示例 -->
        <div class="example-section">
          <h3>我的订单</h3>
          <el-button type="primary" @click="getMyOrders">查看订单</el-button>
          <el-table v-if="orders.length > 0" :data="orders" style="width: 100%; margin-top: 15px">
            <el-table-column prop="orderNo" label="订单编号" />
            <el-table-column prop="totalAmount" label="订单金额" />
            <el-table-column prop="orderStatus" label="订单状态">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.orderStatus)">{{ scope.row.orderStatus }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间" />
          </el-table>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { productAPI, cartAPI, orderAPI } from '../api/index.js'

// 数据定义
const searchKeyword = ref('')
const products = ref([])
const cartItems = ref([])
const orders = ref([])

// 搜索商品
const searchProducts = async () => {
  if (!searchKeyword.value.trim()) {
    ElMessage.warning('请输入搜索关键词')
    return
  }
  
  try {
    const res = await productAPI.searchProducts(searchKeyword.value, {
      page: 1,
      pageSize: 10
    })
    products.value = res.data.list || []
    ElMessage.success('搜索成功')
  } catch (error) {
    console.error('搜索失败:', error)
    ElMessage.error('搜索失败，请稍后重试')
  }
}

// 添加商品到购物车
const addProductToCart = async (product) => {
  try {
    await cartAPI.addToCart({
      productId: product.id,
      quantity: 1,
      skuId: product.skuList ? product.skuList[0].id : ''
    })
    ElMessage.success('已成功加入购物车')
  } catch (error) {
    console.error('加入购物车失败:', error)
    ElMessage.error('加入购物车失败，请稍后重试')
  }
}

// 获取购物车列表
const getCartItems = async () => {
  try {
    const res = await cartAPI.getCartList()
    cartItems.value = res.data || []
    ElMessage.success('获取购物车成功')
  } catch (error) {
    console.error('获取购物车失败:', error)
    ElMessage.error('获取购物车失败，请稍后重试')
  }
}

// 从购物车删除
const removeFromCart = async (cartItemId) => {
  try {
    await cartAPI.removeFromCart(cartItemId)
    // 重新获取购物车列表
    await getCartItems()
    ElMessage.success('删除成功')
  } catch (error) {
    console.error('删除失败:', error)
    ElMessage.error('删除失败，请稍后重试')
  }
}

// 获取我的订单
const getMyOrders = async () => {
  try {
    const res = await orderAPI.getOrderList({
      page: 1,
      pageSize: 5
    })
    orders.value = res.data.list || []
    ElMessage.success('获取订单成功')
  } catch (error) {
    console.error('获取订单失败:', error)
    ElMessage.error('获取订单失败，请稍后重试')
  }
}

// 根据订单状态返回标签类型
const getStatusType = (status) => {
  switch (status) {
    case '待支付':
      return 'warning'
    case '待发货':
      return 'info'
    case '待收货':
      return 'primary'
    case '已完成':
      return 'success'
    case '已取消':
    case '已退款':
      return 'default'
    default:
      return 'info'
  }
}
</script>

<style scoped>
.api-example {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-content {
  padding: 10px 0;
}

.example-section {
  margin-bottom: 30px;
}

.example-section h3 {
  margin-bottom: 15px;
  font-size: 16px;
  font-weight: 600;
}

.cart-items {
  margin-top: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 10px;
}

.cart-item {
  display: flex;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.cart-item:last-child {
  border-bottom: none;
}

.cart-item span {
  margin-right: 20px;
  flex: 1;
}
</style>